import React, { useState, useEffect, useRef, createContext } from 'react';
import styles from './index.module.scss';
import WrapperPage from '@/components/WrapperPage';
import CustomIcon from '@/components/CustomIcon';

import { ResponsiveGrid, Search, Button, Message, Loading } from '@alifd/next';

import CardsView from './components/CardsView';
import TableView from './components/TableView';

export const ChildrenContext = createContext({});

// 获取api
import { getDevices, putTunnels } from './services/devices.js';

const { Cell } = ResponsiveGrid;

const Devices = (props) => {
  const [ showTable, onShowTable ] = useState(false),
        [ showLoading, onShowLoading ] = useState(false);

  // 请求设备列表数据
  let [data,onData] = useState([]),
      [sel, onSel] = useState({});

  const handleUpdate = () => {
    onShowLoading(true)
    getDevices().then(res => {
      console.log(res)
      if(res.code == 200) {
        onData(res.msg);
      } else {
        Message.error({
          content: res.msg,
          duration: 1000
        });
      }
      onShowLoading(false)
    }).catch(e => {
      Message.error('Unknown Error')
      onShowLoading(false)
    });
  };

  useEffect(()=> {
    handleUpdate();
    // 定时器
    let timer = setInterval(() => {
      handleUpdate()
    }, 15000)
    return () => {
      // 组件销毁时，清除定时器
      clearInterval(timer)
    };
  },[]);

  const createTunnels = () => {
    if( sel.length >= 2 ) {
      console.log(sel)
      let obj = {};
      sel.forEach(item=>{
        obj[item] = true;
      })
      putTunnels(obj).then(res => {
        if(res.code == 200) {
          Message.success(res.msg)
        } else {
          Message.error(res.msg)
        }
      })
    } else {
      Message.notice('请选择至少两个设备')
    }
    
  }

  return (
    <WrapperPage path={props.location.pathname}>
      <Loading visible={showLoading}>
      <div className={styles["devices-note"]}>Note: Up to 3 devices are allowed for free. Additional devices are presented only if a valid payment method is in the system.</div>
      <div className={styles["devices-content"]}>
        <ResponsiveGrid device="desktop" className={styles['content-filter']}>
          <Cell colSpan={6}>
            <span className={styles['search-zone']}>
              <Search type="normal" shape="simple" placeholder="Filter by device attributes" />
              <Button type="primary" style={{marginLeft: '4px'}}>Clear Filters</Button>
            </span>
          </Cell>
          <Cell colSpan={6}>
            <span className={styles['button-zone']}>
              {
                sel.length > 0 && (
                  <Button type="primary" onClick={createTunnels} className={`${styles['left']}`}>
                    Create Tunnels
                  </Button>
                )
              }
              <Button type="primary" className={`${styles['left']} round-button`} onClick={handleUpdate}>
                <CustomIcon type="iconsync"/>
              </Button>
              <Button.Group className={styles['middle']}>
                  <Button type={showTable ? 'normal' : 'secondary' } onClick={()=>{onShowTable(false);onSel([])}} style={{padding:'0 10px'}}>
                    <CustomIcon type="iconappstore"/>
                  </Button>
                  <Button type={showTable ? 'secondary' : 'normal'} onClick={()=>{onShowTable(true);onSel([])}}  style={{padding:'0 10px'}}>
                    <CustomIcon type="iconunorderedlist"/>
                  </Button>
              </Button.Group>
              <Button type="secondary" className={styles['right']} style={{padding:'0 10px'}}>
                <CustomIcon type="iconfile-excel"/>
              </Button>
            </span>
          </Cell>
        </ResponsiveGrid>
        <div className={styles['content-display']}>
          {
            showTable ? (
              <ChildrenContext.Provider value={sel}>
                <TableView 
                  onSel={onSel} 
                  rowData={data}
                />
              </ChildrenContext.Provider> 
            ) : (
              <ChildrenContext.Provider value={sel}>
                <CardsView onSel={onSel} rowData={data}/>
              </ChildrenContext.Provider>
            ) 
          }
        </div>
      </div>
      </Loading>
    </WrapperPage>
  );
};

export default Devices;
